package com.wan.personnel2.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wan.personnel2.common.Const;
import com.wan.personnel2.entity.UserInf;
import com.wan.personnel2.dao.UserInfMapper;
import com.wan.personnel2.service.UserInfService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wan.personnel2.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;
import java.util.Date;

@Service
public class UserInfServiceImpl extends ServiceImpl<UserInfMapper, UserInf> implements UserInfService {
    @Autowired
    private UserInfMapper mapper;


    public IPage<UserInf> getUserPageWithName(String loginname,Integer pageNum) {
        IPage<UserInf> page = new Page<UserInf>(pageNum,5);
        IPage<UserInf> loginname1 = mapper.selectPage(page, new QueryWrapper<UserInf>().like(StringUtils.isNotEmpty(loginname),"loginname",loginname));
        return loginname1;
    }

    public boolean delUserInf(Integer id) {
        if (mapper.deleteById(id)>0) {
            return true;
        }
        return false;
    }

    public boolean addUserInf(UserInf user) throws NoSuchAlgorithmException {
        user.setStatus(Const.IS_USER);
        user.setCreatedate(new Date());
        user.setPassword(MD5Utils.repeat(user.getPassword(),user.getUsername()));
        boolean insert = user.insert();

        return insert;
    }


    public UserInf dologin(String loginname, String password) throws NoSuchAlgorithmException {
        if (StringUtils.isNotEmpty(loginname) && StringUtils.isNotEmpty(password)) {
            UserInf user = mapper.selectOne(new QueryWrapper<UserInf>().eq("loginname", loginname));

            if (user != null && user.getPassword().equals(MD5Utils.repeat(password, user.getUsername()))) {
                return user;
            }

        }
        return null;
    }

}
